#pragma once
#include <iostream>
#include <string>
#include "log.hpp"
#include "translation.hpp"

extern Log log;
Init init;
enum
{
    Divzero = 1,
    Modzero,
    Unknown
};

class Task
{
public:
    Task()
    {
    }
    Task(int fd, const std::string &ip, const uint16_t &port) : sockfd_(fd), clientip_(ip), clientport_(port)
    {
    }
    void run()
    {
        char buff[4096];
        ssize_t n = read(sockfd_, buff, sizeof(buff));
        if (n > 0)
        {
            buff[n] = 0;
            std::cout << "client Key@ " << buff << std::endl;
            std::string massege =init.translation(buff);

            //在服务器Run函数开始，把SIGPIPE忽略，防止服务器当读端关闭或者文件描述符关闭时收到这个信号导致服务器关闭
            //就像管道读端关闭，写端就会收到信号而终止进程
            n=write(sockfd_, massege.c_str(), massege.size());
            if(n<0)
            {
                log(Warning,"write err,errno: %d,errstring: %s",errno,strerror(errno));
            }

        }
        else if (n == 0)
        {
            log(Info, "%s:%d quit, server close sockfd: %d", clientip_.c_str(), clientport_, sockfd_);
        }
        else
        {
            log(Warning, "read error, sockfd: %d, client ip: %s, client port: %d", sockfd_, clientip_.c_str(), clientport_);
        }
        close(sockfd_);
    }
    void operator()()
    {
        run();
    }

private:
    int sockfd_;
    std::string clientip_;
    uint16_t clientport_;
};